﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace Milan.Diagnostics
{
	/// <summary>
	/// Queries a status server
	/// </summary>
	public class StatusClient : Milan.Net.RpcClient
	{
		public StatusClient( string moduleName, int processId, string appmode ) : base(GetPipeName(moduleName, appmode, processId),10000)
		{
		}
		public static string GetPipeName(string processName, string appmode, int processId)
		{
			if (appmode == null)
				appmode = "_default";
			return "\\milan.status." + processName + "." + appmode + "." + processId.ToString();
		}
		/// <summary>
		/// Get the process ids of all processed with the given module name
		/// </summary>
		/// <param name="processName">Process name to get all the ids from</param>
		/// <returns>Array of ids </returns>
		public static int[] GetProcessIds(string processName)
		{
			Process[] processlist = Process.GetProcesses();
			List<int>	ids = new List<int>();
			foreach (var process in processlist)
			{
				if (process.ProcessName == processName)
					ids.Add(process.Id);
			}
			return ids.ToArray();
		}
		/// <summary>
		/// Sub directories start with /, all other values are values
		/// </summary>
		/// <param name="baseDirectory"></param>
		/// <returns>list of files and directories</returns>
		public string[] GetKeyList(string baseDirectory ="/")
		{
			string list = Transact("dir " + baseDirectory);
			return list.Split('\n');
		}
		/// <summary>
		/// Returns the name value pairs
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public string GetValue(string path)
		{
			return Transact("get " + path);
		}
		/// <summary>
		/// Requests that the given process terminates.
		/// </summary>
		/// <param name="milliseconds"></param>
		/// <returns></returns>
		public bool RequestQuit(int milliseconds)
		{
			return Convert.ToBoolean(Transact("quit"));
		}
	}
}
